import validate from 'wechat-validate'
import { setStorage } from '../../untils/storage'
Page({
  behaviors: [validate],
  data: {
    countDownVisible: false,
    mobile: '',
    code: '',
    PassCode: '',
    redirectURL: '',
  },

  onLoad(options) {
    this.setData({
      redirectURL: options.redirectURl,
    })
  },

  rules: {
    mobile: [
      { required: true, message: '请填写手机号码!' },
      {
        pattern: /^1[3456789]\d{9}$/,
        message: '请检查手机号码是否正确!',
      },
    ],
    PassCode: [
      { required: true, message: '请填写短信验证码!' },
      { pattern: /^\d{6}$/, message: '请检查短信验证码是否正确!' },
    ],
  },

  async getCode() {
    // 单独只验证 mobile 这个数据
    const { valid, message } = this.validate('mobile')
    if (!valid) wx.utils.toast(message)
    else {
      wx.utils.toast('发送验证码')
      const { data: Code } = await wx.http.get(`/code?mobile=${this.data.mobile}`)
      this.setData({
        PassCode: Code.code,
        countDownVisible: true,
      })
    }
  },

  sendForm() {
    // 验证码 rules 中定义的全部数据
    const isAllValid = this.validate('PassCode')
    if (!isAllValid) return true
    // else request api
  },

  async SubmitInfo() {
    const isAllValid = this.validate('PassCode')
    if (!isAllValid) return
    const { code, data: tokenInfo } = await wx.http.post('/login', {
      mobile: this.data.mobile,
      code: this.data.PassCode,
    })
    if (code === 10000) {
      setStorage('token', tokenInfo.token)
      setStorage('refreshToken', tokenInfo.refreshToken)

      wx.switchTab({
        url: `/${this.data.redirectURL}`,
      })
      wx.utils.toast('登录成功!')
    } else wx.utils.toast('提交数据失败')
  },

  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
})
